<template>
<div class="upload-group">
    <div class="upload-box">
        <el-upload ref="uploadRef" v-model="fileList" :action="uploadAction" :headers="uploadHeader" :show-file-list="false" list-type="picture" :on-success="uploadSuccess">
            <el-button class="upload-button" size="small" type="text" icon="el-icon-link">附件</el-button>
        </el-upload>

        <div class="image-box" v-for="(item,key) in images" :key="key">
            <el-image :src="item.url" fit="cover" :preview-src-list="toImages"></el-image>
            <i class="el-icon-delete remove" @click="handleRemove(item, 'image')"></i>
        </div>

        <el-table :data="files" v-if="files.length > 0" border>
            <el-table-column label="文件" prop="name"></el-table-column>
            <el-table-column align="right">
                <template slot-scope="scope">
                    <el-link type="text" :href="scope.row.url" target="_blank" v-if="scope.row.ext == 'pdf'"><i class="el-icon-view"></i></el-link>
                    <el-link type="text" :href="scope.row.url" target="_blank" v-else><i class="el-icon-download"></i></el-link>
                    <el-button type="text" icon="el-icon-close" class="ml10" @click="handleRemove(scope.row, 'file')"></el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <p class="warning">{{placeholder}}</p>
</div>
</template>

<script>
import {
    getToken
} from '@/utils/auth';

export default {
    name: "UploadFiles",
    props: {
        value: {
            type: Array,
            default: function () {
                return [];
            },
        },
        placeholder: {
            type: String,
            default: "请选择附件",
        },
    },
    data() {
        let header = {};
        header["X-Token"] = getToken();

        return {
            uploadAction: process.env.VUE_APP_BASE_API + "/api/system.file/upload",
            uploadHeader: header,
            fileList: []
        }
    },
    computed: {
        images() {
            // fileList根据url判断所有的图片
            return this.fileList.filter(item => /\.(jpe?g|png|gif)$/i.test(new URL(item.url).pathname));
        },
        files() {
            return this.fileList.filter(item => !/\.(jpe?g|png|gif)$/i.test(new URL(item.url).pathname));
        },
        toImages() {
            return this.images.map(item => item.url);
        }
    },
    watch: {
        value: {
            immediate: true,
            handler(val) {
                this.fileList = val;
            },
        },
    },
    methods: {
        uploadSuccess(res, file) {
            if (res.code !== 200) {
                this.$message.error(res.msg);
                return;
            }

            // 根据file规则构建新的对象
            const newFile = {
                ext: res.data.extname,
                name: file.name,
                url: res.data.path,
            };
            // 将新的文件对象添加到fileList中
            this.fileList.push(newFile);

            this.$emit("input", this.fileList);
        },
        handleRemove(file, type) {
            console.log(file, type);
            // 提醒确认删除
            this.$confirm("删除文件, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(() => {
                    // 处理移除逻辑...
                    const index = this.fileList.findIndex(item => item.url === file.url);
                    if (index !== -1) {
                        // 删除文件
                        this.fileList.splice(index, 1);
                    }
                })
                .catch((e) => {
                    console.log(e);
                    this.$message({
                        type: "info",
                        message: e,
                    });
                });
        },
        clearFiles() {
            this.fileList = [];
            this.$refs.uploadRef.clearFiles();
        },
        setFileList(val) {
            // this.$refs.uploadRef.clearFiles();
            this.fileList = val;
        }
    },
};
</script>

<style lang="less" scoped>
.upload-box {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.image-box {
    width: 100px;
    height: 100px;
    border-radius: 4px;
    border: 1px solid #dedede;
    position: relative;

    .el-image {
        width: 100%;
        height: 100%;
    }

    .remove {
        display: none;
        position: absolute;
        top: 3px;
        right: 3px;
        color: #F56C6C;
        opacity: 0.5;
        z-index: 1;
    }

    &:hover {
        .remove {
            display: block;
        }
    }
}

.upload-button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
}

.ml10 {
    margin-left: 10px;
}
</style>
